package com.forever.desgin;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FutureTest {

	public static void main(String[] args) {
		FutureTask<String> future = new FutureTask<String>(new Callable<String>() {
			public String call() {
				// 真正的任务在这里执行，这里的返回值类型为String，可以为任意类型
				try {
					Thread.sleep(6000L);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				return null;
			}
		});

		ExecutorService executor = Executors.newSingleThreadExecutor();
		executor.submit(future);
		try {
			// 取得结果，同时设置超时执行时间为5秒。同样可以用future.get()，不设置执行超时时间取得结果
			String result = future.get(5000, TimeUnit.MILLISECONDS);
			System.out.println(result);
		} catch (InterruptedException e) {
			future.cancel(true);
		} catch (ExecutionException e) {
			future.cancel(true);
		} catch (TimeoutException e) {
			future.cancel(true);
		} finally {
			executor.shutdown();
		}
	}
}